#!/bin/bash
# env init:
#       This script for wsl ubuntu 18.04 ps. repeat is safe
#       if not use root, need sudo.
# History:
## 2019/10/10  by  wesen

# 备份源
cp /etc/apt/sources.list /etc/apt/sources.list.bak
sed -i 's/http:\/\/archive.ubuntu.com\/ubuntu/http:\/\/mirrors.163.com\/ubuntu/g' /etc/apt/sources.list
sed -i 's/http:\/\/security.ubuntu.com\/ubuntu/http:\/\/mirrors.163.com\/ubuntu/g' /etc/apt/sources.list

#更新apt安装常用应用
apt update && apt -y upgrade && apt install -y php-curl php-fpm php-mbstring php-mysql php-xml php-zip php-gd php-dev php-pear php-bcmath composer nginx redis mysql-server libpng-dev


# for safe cgi.fix_pathinfo=0
cp /etc/php/7.2/fpm/php.ini /etc/php/7.2/fpm/php.ini.bak
sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/' /etc/php/7.2/fpm/php.ini

# wsl tcp bug fastcgi_buffering off;
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

grep "fastcgi_buffering off;" /etc/nginx/nginx.conf >/dev/null
if [ $? -ne 0 ]; then
     sed -i 's/sendfile on;/&\n\tfastcgi_buffering off;/' /etc/nginx/nginx.conf
fi

# 下载新版本的node,apt的源太老了
wget https://npm.taobao.org/mirrors/node/v12.11.1/node-v12.11.1-linux-x64.tar.xz
#解压到opt目录下
 tar -xJf node-v12.11.1-linux-x64.tar.xz  -C /opt
#删除node压缩文件
rm -f node-v12.11.1-linux-x64.tar.xz
#建立node和npm的链接
ln -s /opt/node-v12.11.1-linux-x64/bin/node /usr/bin/node
ln -s /opt/node-v12.11.1-linux-x64/bin/npm /usr/bin/npm

#设置npm淘宝镜像
npm config set registry https://registry.npm.taobao.org
#设置composer镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

#添加示例nginx配置文件
cat>/etc/nginx/conf.d/wesen.conf<<EOF
server {
    listen 8080;
    server_name _ ;
    root /mnt/h/www/laravel/public;

    index index.php index.html index.htm;

    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    location ~ \.php$ {
        root           /mnt/h/www/laravel/public;
        #fastcgi_pass   127.0.0.1:9000;
        fastcgi_pass   unix:/run/php/php7.2-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
        include        fastcgi_params;
    }
}
EOF

#创建自启sh
cat>startservers.sh<<EOF
#!/bin/bash
# Edit this for your relevant services.
services=(php7.2-fpm nginx redis-server mysql)
for service in "\${services[@]}"
do
         if (( \$(ps -ef | grep -v grep | grep \$service | wc -l) == 0 ))
         then
         # Uncomment to get messages. #
         #echo "Starting service \${service}"
         (sudo service \$service start > /dev/null &)
         fi
done
EOF
#给与权限及添加到.bashrc中
chmod +x startservers.sh;sed -i '$a ./startservers.sh' .bashrc;